/*
 * BulkServiceImpl.java
 *
 * Created on February 5, 2005, 4:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package org.naga.bulksender.service;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.naga.bulksender.dal.BulkMessageDaoIfc;
import org.naga.bulksender.data.BulkMessage;
import org.naga.bulksender.binding.Device;
import org.smslib.IOutboundMessageNotification;
import org.smslib.IInboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
import org.naga.bulksender.data.SMSBulkContext;

/**
 *
 * @author Naga Services
 *
 * Implementation from the Business Logic 
 */
public class BulkServiceImpl implements BulkServiceIfc {

    private DeviceConfiguration devConfig = null;
    private BulkMessageDaoIfc msgDao = null;
    private static final String SCHD_STATUS = "Scheduled";
    private Log log = LogFactory.getLog(BulkServiceImpl.class);
    private IOutboundMessageNotification outbound = null;
    private IInboundMessageNotification inbound = null;
    private Service srvSms = null;
    private SMSBulkContext bulkCtx = null;

    /** Creates a new instance of BulkServiceImpl */
    public BulkServiceImpl() {
    }

    public void setMessageDao(BulkMessageDaoIfc dao) {
        msgDao = dao;
    }

    /**
     * Check if there is a new messages to Send 
     * @return The list of new Messages identified
     */
    public List<BulkMessage> checkNewMsgToSend() {
        log.debug("Checking for New Messages");
        List<BulkMessage> msgLst = msgDao.getNewMessages();
        for (BulkMessage msg : msgLst) {
            msgDao.getNumbersFromContacts(msg);
            msgDao.getNumbersFromGroup(msg);
            msg.getTotalReceipent();
        }
        return msgLst;
    }

    
    /**
     * Start the SMS Service Provider
     * @throws java.lang.Exception 
     */
    public void startService() throws Exception {
        try {
            log.debug("Start the BulkServiceImpl");
            List<Device> devicesList = this.devConfig.getDevices();
            //Removed , now is Injected
           // this.srvSms = new Service();
            SerialModemGateway gateway = null;
            for (Device dev : devicesList) {
                gateway = new SerialModemGateway(dev.getModemId(), dev.getComPort(), dev.getBaudRate().intValue(), dev.getManufacturer(), dev.getModel());
                gateway.setInbound(true);
                gateway.setOutbound(true);
                gateway.setSimPin("0000");
                srvSms.addGateway(gateway);
            }
            log.debug("OutBound CallBack:>" + outbound);
            log.debug("InBound CallBack:>" + inbound);
            this.srvSms.setOutboundNotification(outbound);
            this.srvSms.setInboundNotification(inbound);
            srvSms.startService();
        } catch (Exception exc) {
            log.error("Exception when try to start the Service", exc);
            throw new Exception(exc);
        }
    }

    public void setDeviceConfig(DeviceConfiguration config) {
        devConfig = config;
    }

    
    /**
     * Stop the SMS Service Provider
     * @throws java.lang.Exception 
     */
    public void stopService() throws Exception {
        try {
            log.debug("Stop the BulkServiceImpl");
            if (srvSms != null) {
                srvSms.stopService();
            }
            //Removed, now the Service is Injected
            //srvSms = null;
        } catch (Exception exc) {
            log.error("Exception when try to stop the Service", exc);
            throw new Exception(exc);
        }

    }

    
    /**
     * Schedule new messages in the SMS Service Provider's Queue
     * @param lstMsg 
     */
    public void scheduleNewMessages(List<BulkMessage> lstMsg) {

        if (null != lstMsg) {
            log.debug(lstMsg.size() + " ::: New Messages");
            for (BulkMessage msg : lstMsg) {
                log.debug("===================================");
                OutboundMessage outMsg = (OutboundMessage) msg;
                String groupName = outMsg.getRecipient();
                this.srvSms.createGroup(groupName);
                log.debug("New Msg=>" + outMsg.getText());

                for (String number : msg.getNumbers()) {
                    log.debug("Manully=>" + number);
                    this.srvSms.addToGroup(groupName, number);
                }
                for (String number : msg.getLstNumberFromContacts()) {
                    log.debug("Number COntacts=>" + number);
                    this.srvSms.addToGroup(groupName, number);
                }
                for (String number : msg.getLstNumberFromGroups()) {
                    log.debug("Number Grupos=>" + number);
                    this.srvSms.addToGroup(groupName, number);
                }
                this.srvSms.queueMessage(outMsg);
                this.bulkCtx.addMessage(msg);
                msgDao.changeMessageStatus(msg.getBulkSmsId(), SCHD_STATUS);
                log.debug("===================================");
            }
        //TODO Schedule the Message to Service
        }
    }

    public void setOutboundNotification(IOutboundMessageNotification obound) {
        outbound = obound;
    }

    public void setInboundNotification(IInboundMessageNotification ibound) {
        inbound = ibound;
    }
    // set the outboundnotification
    //define the implemantation in the applcaitioncontext througth IoC

    public void setBulkContext(SMSBulkContext ctx) {
        bulkCtx = ctx;
    }

    public void setServiceProvider(Service svc){
        this.srvSms = svc;
    }
}